﻿package com.htmlparser;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.InputTag;
import org.htmlparser.tags.LabelTag;
import org.htmlparser.util.NodeList;
import org.jdom.Element;

import java.util.*;;

public class Input {
	public static String html = "";
	static int hidden_id = 0;
	
	//提取表单
	public static Element getInput(InputTag inputTag, Node nextNode) {
		System.out.println("");
		System.out.println("##################  解析<input>开始  ###################");
		System.out.println("");
		
		InputTag input2 = inputTag;
		Element input = null;
		String input_type = (input2.getAttribute("type"));
		String input_value = (input2.getAttribute("value"));
		String input_name = (input2.getAttribute("name"));

		// System.out.println("input_type:"+input_type);
		// System.out.println("input_value:"+input_value);
		// System.out.println("input_name:"+input_name);
		
			if ((input_type == null) ||(input_type.equals("")) || (input_type.equals("text"))) {
				
				//有的<input>没有"type"属性，<input>的默认"type"属性是text
					// 输入框
					input = new Element("in");

					// 文本框名称 ----- <tfName>文本框名称</tfName>
					// 如果输入框的前面是Label标签，或者是纯文本，则把它作为输入框的名称
					// if((lastNode instanceof LabelTag)){
					// String label = ((LabelTag)lastNode).getLabel().trim();
					// //System.out.println("tf_LabelTag:"+Label);
					//				
					// if((label != null)&&!(label.equals(""))){
					// Element tf_name = new Element("nm");
					// tf_name.setText(label);
					// input.addContent(tf_name);
					// }
					//				
					// }
					// if(lastNode instanceof TextNode){
					// String text = lastNode.getText().trim();
					// //System.out.println("tf_TextNode:"+Label);
					//				
					// if((text != null)&&!(text.equals(""))){
					// Element tf_name = new Element("nm");
					// tf_name.setText(text);
					// input.addContent(tf_name);
					// }
					//				
					// }
					// 默认值 ---- <setText>默认值</setText>
					if ((input_value != null) && !(input_value.equals(""))) {
						Element default_text = new Element("txt");
						default_text.setText(input_value);
						input.addContent(default_text);
					} else if (input_name != null) {
						Element default_text = new Element("txt");
						default_text.setText(input_name);
						input.addContent(default_text);
					}
					if (input_name != null) {
						input.setAttribute("nm", input_name);
					}

				} else if (input_type.equals("radio")) {
					//input = new Element("rd");
					/*
					 * if (input2.getAttribute("checked") != null) { String checked =
					 * input2.getAttribute("checked").toString();
					 * //input.setAttribute("checked",checked); } if
					 * (input2.getAttribute("value") != null) { String value =
					 * input2.getAttribute("value").toString(); }
					 * 
					 * //单选按钮后面的name if((input_name != null) &&
					 * !(input_name.equals(""))){ Element radio_name = new
					 * Element("nm"); radio_name.setText(input_name);
					 * input.addContent(radio_name); }
					 * 
					 * //单选按钮后面的文本 if((nextNode instanceof TextNode)&&(nextNode
					 * !=null)){ String text = nextNode.getText().trim();
					 * //System.out.println("tf_TextNode:"+Label);
					 * 
					 * if((text != null)&&!(text.equals(""))){ Element radio_text = new
					 * Element("tx"); radio_text.setText(text);
					 * input.addContent(radio_text); } }
					 */
					//int radio_id = 1;
					//if (radio_id == radio_index) {
						
					if (MyParse62.radio_id < MyParse62.radio_count) {
						MyParse62.radio_id++;
					}else {
						System.out.println("radio_id==" + MyParse62.radio_id + "==");
						System.out.println("ppppppppppppppppppppppppppppppppppppppp");
						input = getRadio();
					}

						// System.out.println("input---name:"+input.getName());
						//				
						// List list = input.getChildren();
						// Iterator iterator = list.iterator();
						// int i = 0;
						// while(iterator.hasNext()){
						// System.out.println("~~~~~~~~~~~"+i+"~~~~~~~~~~"+((Element)iterator.next()).getText());
						// i++;
						// }
//						radio_index = 0;
//					} else {
//						System.out.println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
//						radio_id++;
//						input = null;
//					}
				}

				else if (input_type.equals("checkbox")) {
					input = new Element("ckb");

					// 多选按钮后面的name
					if ((input_name != null) && !(input_name.equals(""))) {
						Element checkbox_name = new Element("nm");
						Element text = new Element("txt");
						String txt = "";
						if (nextNode instanceof LabelTag) {
							txt = ((LabelTag)nextNode).getLabel();
						} else if(nextNode instanceof TextNode){
							txt = nextNode.getText().trim();
						}
						text.setText(txt);
						checkbox_name.setText(input_name);
						input.addContent(checkbox_name);
						input.addContent(text);
					}

					// 多选按钮后面的文本
//					if ((nextNode instanceof TextNode) && (nextNode != null)) {
//						String Label = nextNode.getText().trim();
//						Element checkbox_text = new Element("tx");
//						checkbox_text.setText(Label);
//						input.addContent(checkbox_text);
//					}
				} else if (input_type.equals("submit")) {
					input = new Element("smt");
					if ((input_value != null) && !(input_value.equals(""))) {
						Element value = new Element("smtNm");
						value.setText(input_value);
						input.addContent(value);
					} else {
						Element value = new Element("smtNm");
						value.setText("submit");
						input.addContent(value);
					}
					
					//把该提交按钮的url设为对应的form的action的内容。
					Element url = new Element("url");
					String submit_url = MyParse62.smt_url;
					if((submit_url != null) && !(submit_url.equals(""))){
						//如果路径是../开头
						if(String.valueOf(submit_url.charAt(0)).equals(".")){
							submit_url = submit_url.substring(3, submit_url.length());
							submit_url = MyParse62.path.replaceAll("show/", "") + submit_url;
						}
						//如果路径前没有/
						else if(!(String.valueOf(submit_url.charAt(0)).equals("/"))){
							submit_url = MyParse62.path + submit_url;
						}
					}
					url.setText(submit_url);
					//input.addContent(url);

				} else if (input_type.equals("reset")) {
					input = new Element("rst");
				} else if (input_type.equals("button")) {
					// 按键
					input = new Element("bt");

					// 按钮的文本 ---- <buttonName>按键名称</buttonName>
					Element button_text = new Element("btNm");
					if (input != null) {
						if (input_value != null && !input_value.equals("")) {
							button_text.setText(input_value);
						} else if (input_name != null && !input_name.equals("")) {
							button_text.setText(input_name);
						}
						input.addContent(button_text);
					}

					// 按钮的onclick()事件 ---- <url>URL</url>
					String button_onclick = input2.getAttribute("onclick");

					if ((button_onclick != null) && !(button_onclick.equals(""))
							&& (button_onclick.indexOf("location") == -1)
							&& (button_onclick.indexOf("window") == -1)
							&& (button_onclick.indexOf("document") == -1)) {

						System.out.println("");
						System.out.println("【"+input_value+"】这个按钮<button>里没有window/document/location");

						String jsResult = "";
						// 取input button中的链接地址
						// jsMethod : button的onclick事件的方法名，不含括号
						System.out.println("button_onclick=" + button_onclick + "=");

						String href = button_onclick.replaceAll(";", "");
						// if(href.indexOf(".") == -1){
						int begin = button_onclick.indexOf("(");
						System.out.println("begin=" + begin + "=");
						String jsMethod = button_onclick.substring(0, begin)
								.replaceAll("'", "");
						String[] args = Util.getHrefParameters(href, jsMethod);
						for (String s : args) {
							// System.out.println("<button> -- args="+s+"=");
						}

						// 判断参数是否为数字
						// 防止参数为空时，抛出数据转换异常
						if (args != null) {
							Object[] oParameters = new Object[args.length];
							for (int i = 0; i < args.length; i++) {
								if (Util.isNumeric(args[i])) {
									oParameters[i] = Util.parameters_String2Float(args[i]);
								} else {
									oParameters[i] = args[i];
								}
							}

							String bt_text = "";
							if ((input_value != null) && !(input_value.equals(""))) {
								bt_text = input_value;
							} else if ((input_name != null) && !(input_name.equals(""))) {
								bt_text = input_name;
							} else {
								bt_text = "###";
							}
							System.out.println("");
							System.out.println("====================== button调用 getScript 开始 =======================");
							System.out.println("");
							System.out.println("button【" + bt_text+ "】传递的参数数组oParameters[]：                       ");
							for (int i = 0; i < oParameters.length; i++) {
								System.out.println("oParameters[" + i + "]=="
										+ oParameters[i] + "==");
							}

							jsResult = JavaScript_parser.getScript(jsMethod, oParameters);
							System.out.println("Input调用getScript后得到的URL：jsResult###" + jsResult + "###");
							System.out.println("");
							System.out.println("====================== button调用  getScript 结束 =======================");
							System.out.println("");
						}
						// System.out.println("jsResult: "+jsResult);
						if (jsResult != null) {
							Element onclick = new Element("url");
							onclick.setText(jsResult);
							input.addContent(onclick);
						}
					} else {
						// window.close()
						System.out.println("");
						System.out.println("【"+input_value+"】这个按钮<button>里有window/document/location");

						if (button_onclick.indexOf("window.close") > -1) {
							Element onclick = new Element("url");
							onclick.setText("window.close()");
							input.addContent(onclick);
						}

						if (button_onclick.indexOf("window.open") > -1) {
							int b1 = button_onclick.indexOf("open");
							int b2 = button_onclick.indexOf(",", b1);
							String temp = "";
							if (b2 > -1) {
								temp = button_onclick.substring(b1 + 5, b2).replaceAll(
										"'", "").replaceAll("\"", "");
							} else {
								int b3 = button_onclick.indexOf(")", b1);
								temp = button_onclick.substring(b1 + 5, b3).replaceAll(
										"'", "").replaceAll("\"", "");
							}

							Element onclick = new Element("url");
							onclick.setText(temp);
							input.addContent(onclick);
						} else if (((button_onclick.indexOf("window") > -1) || (button_onclick
								.indexOf("location") > -1))
								&& (button_onclick.indexOf("=") > -1)) {
							int b1 = button_onclick.indexOf("=");
							String temp = button_onclick.substring(b1 + 1).replaceAll(
									"'", "").replaceAll(";", "");
							Element onclick = new Element("url");
							onclick.setText(temp);
							input.addContent(onclick);
						}

						if ((button_onclick.indexOf("document") > -1)
								&& (button_onclick.indexOf("=") > -1)) {
							int b1 = button_onclick.indexOf("=");
							String temp = button_onclick.substring(b1 + 1).replaceAll(
									"'", "").replaceAll(";", "");
							;
							Element onclick = new Element("url");
							onclick.setText(temp);
							input.addContent(onclick);
						}
					}
				}
			System.out.println("");
			System.out.println("#################  解析<input>结束  #################");
			System.out.println("");
			
			//TODO 当input不包含元素时，设为null，不给手机端传值
			
			if (input != null) {
				List list = input.getChildren();
				if (list.size() == 0) {
					input = null;
				}
			}
			
			
			
		return input;
	}

	//TODO "转存"跳转到的页面，没有取到radio
	//单独提取单选radio
	public static Element getRadio(){
		System.out.println("");
		System.out.println("#################  解析<radio>开始  ##################");
		System.out.println("");
		
		NodeList InputList = null;
		Parser parser = null;
		String name = "";
		String id = "";
    
		//提取当前页面所有的<input>标签
		try {
			parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("GBK");
			NodeFilter InputFilter = new NodeClassFilter(InputTag.class);
			InputList = parser.extractAllNodesThatMatch(InputFilter);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Element radio = new Element("rd");
		int j = 0;
		for (int i = 0; i < InputList.size(); i++) {

			Node node = InputList.elementAt(i);
			InputTag input = (InputTag) node;
			String type = input.getAttribute("type");
			String value = input.getAttribute("value");

			if (input != null) {
				if ((type != null)&&!(type.equals(""))) {
					if (type.equals("radio")) {
						MyParse62.radio_count++;
						name = input.getAttribute("name");
						id = input.getAttribute("id");
						Node node2 = input.getNextSibling();
						//System.out.println("node2=" + node2 + "=");
						String nextNodeText = "";
						if((node2 instanceof InputTag) && (((InputTag)node2).getAttribute("type").equals("text"))){
							nextNodeText = ((InputTag)node2).getAttribute("value");
						}else if((node2 instanceof LabelTag)){
							nextNodeText = ((LabelTag)node2).getLabel();
						}else if(node2 instanceof TextNode){
							nextNodeText = node2.getText().trim().replaceAll("\r\n", "");
						}else if(node2 instanceof ImageTag){
							nextNodeText = "";
						}

						Element text = new Element("txt");
						text.setText(nextNodeText);
						radio.addContent(text);
						
						Element radio_value = new Element("value");
						radio_value.setText(value);
						radio.addContent(radio_value);

						j++;
					}
				}
			}
		}
		Element radio_name = new Element("nm");
		if((name != null)&& !(name.equals(""))){
			radio_name.setText(name);
		}else if((id != null)&& !(id.equals(""))){
			radio_name.setText(id);
		}else{
			radio_name.setText("");
		}
		radio.addContent(radio_name);
		
		System.out.println("");
		System.out.println("####################  解析<radio>结束  ##################");
		System.out.println("");
		
		return radio;
	}
	//TODO 隐藏域 单独提取单选hidden
	public static String getHidden(){
		
		
		NodeList InputList = null;
		Parser parser = null;
		String name = "";
		String value = "";
		String id = "";
		String allHidden = "";
		StringBuffer allHidden_Buffer = new StringBuffer();
		int j = 0;

		//提取当前页面所有的<input>标签
		try {
			parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("GBK");
			NodeFilter InputFilter = new NodeClassFilter(InputTag.class);
			InputList = parser.extractAllNodesThatMatch(InputFilter);
		} catch (Exception e) {
			e.printStackTrace();
		}

		for (int i = 0; i < InputList.size(); i++) {

			Node node = InputList.elementAt(i);
			InputTag input = (InputTag) node;
			String type = input.getAttribute("type");
			
			if (input != null) {
				if ((type != null)&&!(type.equals(""))) {
					if (type.equals("hidden")) {
						System.out.println("");
						System.out.println("#################  解析<hidden>开始  ##################");
						System.out.println("");
						
						name = input.getAttribute("name");
						value = input.getAttribute("value");
						id = input.getAttribute("id");
						
						System.out.println("【hidden_name】==" + name + "==");
						System.out.println("【hidden_value】==" + value + "==");
						
						if (value == null) {
							value = "";
						}
						
						if (name != null) {
							allHidden_Buffer.append(name+"="+value+"&");
						}
						
						if (name != null) {
							if (value != null) {
								MyParse62.hiddens.put(name, value);
							}
						}
						//TODO 数组越界--MyParse62.hiddenNames[hidden_id] = name;
						MyParse62.hiddenNames[hidden_id] = name;
						System.out.println("MyParse62.hiddenNames["+hidden_id+"]##" + MyParse62.hiddenNames[hidden_id] + "##");
						hidden_id++;
					}
				}
			}
		}
		allHidden = allHidden_Buffer.toString();
		
		if (allHidden.length()>0) {
			System.out.println("");
			System.out.println("####################  隐藏域 start  ##################");
			System.out.println(allHidden);
			System.out.println("####################  隐藏域 end  ##################");
			System.out.println("");
			
			System.out.println("");
			System.out.println("####################  解析<hidden>结束  ##################");
			System.out.println("");
		}
		
		
		return allHidden;
	}
}
